<?php

class JSONDB
{
	var $dir = null;

	function __construct($dir){
		$this->dir=$dir."/";
	}	
	
	function file_list(){
		$tables=array();
		if ($dh = opendir($this->dir)) {
	    	while (($file = readdir($dh)) !== false) {
	       	   if($file == "." || $file==".."||preg_match('/^\./',$file)){
	       	   		continue;
	       	   }
	           $tables[]=$file;  
	       }
	       closedir($dh);
		}
		return $tables;
	}
	
	function all(){
		$files = $this->file_list();
		$json=array();
		foreach($files as $file){
			$json[] = json_decode(file_get_contents($this->dir.$file));
		}
		return $json;
	}

	
	function set($file_name,$data){
		$data_json = json_encode($data);	
		$handle = fopen($this->dir.$file_name, 'w');
		fwrite($handle, $data_json); 
		fclose($handle);	
	}
	
	function get($file_name){
		return json_decode(file_get_contents($this->dir.$file_name));
	}
	
 
	
	function delete($file_name){
		copy($this->dir.$file_name,ROOT."trash/".time()."-".$file_name); 
  	unlink($this->dir.$file_name); 
	}			

	function size(){
		$bytes=filesize(SAFEPATH.$this->tablename);
        $s = array('B', 'Kb', 'MB', 'GB', 'TB', 'PB');
        $e = floor(log($bytes)/log(1024));
        return sprintf('%d '.$s[$e], ($bytes/pow(1024, floor($e))));
	}

	function randoms($num=10){
		srand((double)microtime()*1000000);
		$all=$this->peeks(array());
		$return=array();
		$has=array();
		for($i=0;$i<$num;$i++){
			$ok=rand()%count($all);
			if($has[$ok]==1){
				continue;
			}		
			$has[$ok]=1;			
			$return[]=$all[$ok];
		}
		return $return;		
	}
	
}
?>